using UnityEngine;
using System;

namespace Prota.Unity
{
    
    // 让 RectTransform 正好覆盖相机.
    [ExecuteAlways]
    public class SyncRectTransformToCamera : MonoBehaviour
    {
        public float zOffset = 0;
        
        public Camera syncToCamera;
        
        
        void Update()
        {
            SyncToCamera();
        }
        
        public void SyncToCamera()
        {
            var syncToCamera = this.syncToCamera;
            if(!this.syncToCamera) syncToCamera = Camera.main;
            
            var height = syncToCamera.orthographicSize * 2;
            
            if(this.TryGetComponent<SurfaceRenderer>(out var srd))
            {
                srd.zNear = syncToCamera.nearClipPlane;
                srd.zFar = syncToCamera.farClipPlane;
                srd.pixelPerUnit = syncToCamera.pixelHeight / height;
            }
                
            var tr = this.transform;
            if(tr is RectTransform rt)
            {
                rt.position = syncToCamera.transform.position + Vector3.forward * zOffset;
                rt.rotation = syncToCamera.transform.rotation;
                rt.sizeDelta = new Vector2(height * syncToCamera.aspect, height);
            }
            else
            {
                tr.position = syncToCamera.transform.position + Vector3.forward * zOffset;
                tr.rotation = syncToCamera.transform.rotation;
                tr.localScale = new Vector3(height * syncToCamera.aspect, height, 1);
            }
            
        }
    }
}
